import {
  createBrowserRouter,
  Navigate,
  RouteObject,
  RouterProvider,
} from "react-router-dom";
import baseRoutes from "./router";
import { useEffect, useState } from "react";
import generateRoutes from "./utils/generateRoutes";
import { useDispatch, useSelector } from "react-redux";
import { StateType } from "./store";
import { getMemuList } from "./services/api/user";
import { setMenu } from "./store/user/authSlice";

function App() {
  const dispatch = useDispatch();
  const { token } = useSelector((state: StateType) => state.authSlice);
  const [router, setRouter] = useState<any>(null);
  // 在登录成功后，生成唯一的 key 强制重新挂载 RouterProvider
  // 解决登录跳转到首页时，默认子路由没有渲染的问题
  const [routerKey, setRouterKey] = useState(0);

  useEffect(() => {
    async function loadData() {
      // 加载菜单数据，生成动态路由
      const menuList = await getMemuList();
      const dynamicRoutes = generateRoutes(menuList);

      // 合并基础路由+动态路由
      const newRoutes = mergeRoutes(baseRoutes, dynamicRoutes);

      dispatch(setMenu(menuList));
      setRouter(createBrowserRouter(newRoutes));
      setRouterKey((prev) => prev + 1);
    }

    loadData();
  }, [token]);

  return router ? <RouterProvider key={routerKey} router={router} /> : <></>;
}

export default App;

/**
 * @param baseRoutes 基础路由表
 * @param dynamicRoutes 动态路由表
 * @returns 合并后的路由表
 */
function mergeRoutes(
  baseRoutes: RouteObject[],
  dynamicRoutes: RouteObject[]
): any {
  if (dynamicRoutes.length === 0) {
    return baseRoutes;
  }

  const myRoutes = [...baseRoutes];

  return myRoutes.map((route) => {
    if (route.path === "/") {
      return {
        ...route,
        children: [
          // 保留原有的子路由（如果有）
          ...(route.children || []),
          // 设置默认子路由
          // { index: true, element: dynamicRoutes[0].element},
          // 添加其他动态路由
          ...dynamicRoutes,
          // 重定向到默认子路由
          { path: "", element: <Navigate to={dynamicRoutes[0].path!} /> },
        ],
      };
    }

    return route;
  });
}
